﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Pixster.Controllers.Helpers
{
    public static class XmlSerializer<T>
    {
        /// <summary>
        /// XML serializer for class
        /// </summary>
        static readonly XmlSerializer Serializer = new XmlSerializer(typeof(T));

        /// <summary>
        /// Serialize object into XML string
        /// </summary>
        /// <param name="myobject">Object to be serialized</param>
        /// <returns>String</returns>
        public static String Serialize(T myobject)
        {
            try
            {
                if (myobject == null) return null;

                using (var ms = new MemoryStream())
                {
                    using (var writer = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true }))
                    {
                        if (writer != null)
                        {
                            Serializer.Serialize(writer, myobject);
                            ms.Seek(0, SeekOrigin.Begin);
                            using (var reader = new StreamReader(ms, System.Text.Encoding.UTF8))
                            {
                                reader.ReadToEnd();
                                writer.Close();
                                reader.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// Deserialize object into an instance of T
        /// </summary>
        /// <param name="xml">Serialized XML string</param>
        /// <returns>Object of type T</returns>
        public static T Deserialize(String xml)
        {
            try
            {
                if (!String.IsNullOrEmpty(xml))
                {
                    using (var sr = new StringReader(xml))
                    {
                        return (T)Serializer.Deserialize(sr);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return default(T);
        }
    }
}